package com.zzj.seckill.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class AccessLimitInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = ((HandlerMethod) handler);
            AccessLimit methodAnnotation = hm.getMethodAnnotation(AccessLimit.class);
            if(methodAnnotation == null){
                return true;
            }
            int second = methodAnnotation.second();
            int i = methodAnnotation.maxCount();
//            boolean b = methodAnnotation.needLogin();
            String key = request.getRequestURI();
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Integer num = ((Integer) valueOperations.get("uri:" + request.getRequestURI()));
            if(null == num){
                valueOperations.set("uri:"+request.getRequestURI(),0,5, TimeUnit.SECONDS);
            }else if(num < i){
                valueOperations.increment("uri:"+request.getRequestURI());
            }else{
                return false;
            }

        }

        return true;
    }
}
